use std::{error::Error, fs};

pub struct Config2 {
  pub filename:String,
  pub query:String,
}

impl Config2 {
  pub fn new(args: &Vec<String>) -> Result<Config2,  &'static str> {
    println!("结果:{:?}", args);
    if args.len() < 3 {
      return Err("长度有问题");
    }
    let query = args[1].clone();
    let filename = args[2].clone();
    Ok(Config2 { filename: filename, query: query })
  }
}

pub fn run(config: Config2) -> Result<(), Box<dyn Error>> {
  println!("文件名:{},查询:{}", config.filename, config.query);
  let contents = fs::read_to_string(config.filename).expect("文件读取失败");
  println!("文件内容:{}", contents);
  for line in search(&config.query, &contents) {
    println!("{}", line);
  }
  Ok(())
}

pub fn search<'a>(query:&str, contents:&'a str) -> Vec<&'a str> {
  let mut result = Vec::new();
  for line in contents.lines() {
    if line.contains(query) {
      result.push(line);
    }
  }
  result
}